package top.soeasy.framework.security.provider;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Component;
import top.soeasy.common.constant.Constants;
import top.soeasy.common.core.redis.RedisCache;
import top.soeasy.framework.security.token.MobileCodeAuthenticationToken;

// implements AuthenticationProvider
@Component
public class MobileCodeAuthenticationProvider implements AuthenticationProvider {

    @Autowired
    @Qualifier("mobileCodeUserDetails")
    private UserDetailsService userDetailsService;
    @Autowired
    private RedisCache redisCache;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        String phone = (String) authentication.getPrincipal();
        String codeKey = Constants.PHONE_CODE_KEY + phone;
        String code = (String) authentication.getCredentials();
        String codeCache = redisCache.getCacheObject(codeKey);
        if (codeCache == null) {
            throw new BadCredentialsException("验证码过期或者未发送！");
        }
        if (!codeCache.equals(code)) {
            throw new BadCredentialsException("验证码错误！");
        }
        UserDetails user = userDetailsService.loadUserByUsername(phone);
        return new UsernamePasswordAuthenticationToken(user,"",authentication.getAuthorities());
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return (MobileCodeAuthenticationToken.class.isAssignableFrom(authentication));
    }

}
